package org.jeecg.modules.system.util;

import com.alibaba.fastjson.JSONObject;
import fr.opensagres.xdocreport.utils.StringUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class TemplateMessageUtil {

    private final RedisUtil redisUtil;

    @Value(value = "${uni-app.appid}")
    private String appid;
    @Value(value = "${uni-app.secret}")
    private String secret;

    public TemplateMessageUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public boolean getSendMessage(String touser, String value1, String value2, String value3) {
        String path="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getToken();
        String template_id = "gIGGKexGQiKF9VHfeOTkAMyCZLZtezxWYF2kFqAIHlY";
        String url = "http://xiangmuguanli.tw-tj.com";
        JSONObject jsonObj=new JSONObject();
        jsonObj.put("touser",touser);
        jsonObj.put("template_id",template_id);
        jsonObj.put("url", url);
        JSONObject data=new JSONObject();
        JSONObject thing2=new JSONObject();
        thing2.put("value",value1);
        JSONObject short_thing3=new JSONObject();
        short_thing3.put("value",value2);
        JSONObject time5=new JSONObject();
        time5.put("value",value3);
        data.put("thing2",thing2);
        data.put("short_thing3",short_thing3);
        data.put("time5",time5);
        jsonObj.put("data",data);
        JSONObject result= RestUtil.post(path,jsonObj);
        if(result.getInteger("errcode")==0){
            return true;
        }
        return false;
    }

    public String getToken() {
        if(redisUtil.hasKey("wx_token")){
            Object token=redisUtil.get("wx_token");
            if(token!=null&& StringUtils.isNotEmpty(token.toString())){
                return token.toString();
            }else{
                redisUtil.set("wx_token",getWXToken(),7000);
            }
        }else{
            redisUtil.set("wx_token",getWXToken(),7000);
        }
        return redisUtil.get("wx_token").toString();
    }

    public String getWXToken() {
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid + "&secret=" + secret;
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObj = JSONObject.parseObject(forObject);
        if(jsonObj.containsKey("access_token")){
            return jsonObj.getString("access_token");
        }
        return "";
    }
}
